package com.kfm.controller;

import com.kfm.model.Account;
import com.kfm.model.group.AccountGroupForSave;
import com.kfm.model.group.AccountGroupForUpdate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

/**
 * 双端校验
 *   客户端、服务端
 */
@Controller
public class ValController {

    @RequestMapping("/valid")
    public ModelAndView valid(ModelAndView mv, @Valid Account account, BindingResult bindingResult, Errors errors){
        List<ObjectError> allErrors = errors.getAllErrors();
        String defaultMessage = null;
        for (ObjectError error : allErrors){
            defaultMessage = error.getDefaultMessage();
            System.out.println(defaultMessage);
        }
        // 视图及数据的对象
        mv = new ModelAndView("hello");
        if (errors.hasErrors()){
            // 页面发送内容
            mv.addObject("msg", defaultMessage);
        }
        System.out.println(account);
        return mv;
    }

    @PostMapping("/saveaccount")
    public String save(@Validated(AccountGroupForSave.class) Account account, Errors errors){
        return "hello";
    }

    @PutMapping("/saveaccount")
    public String update(@Validated(AccountGroupForUpdate.class) Account account, Errors errors){
        return "hello";
    }
}
